package com.free.framework.lib.network;

import com.free.framework.constants.Const;
import com.free.framework.lib.utils.AppInfo;
import com.free.framework.lib.utils.ContextHolder;
import com.free.framework.lib.utils.DeviceInfo;
import com.free.framework.lib.utils.SysInfo;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author 李博
 * @date 2016年11月01日
 * @desc
 */
public class CommonHeaderInterceptor implements Interceptor {

    private static volatile CommonHeaderInterceptor mCommonHeaderInterceptor;
    private HashMap<String, String> mHeaders;

    private CommonHeaderInterceptor() {
        mHeaders = new HashMap<>();
        mHeaders.put(Const.CommonHttpHeader.PL, Const.CommonHttpHeader.PL_ANDROID);
        mHeaders.put(Const.CommonHttpHeader.RL, DeviceInfo.getScreenSize(ContextHolder.getContext()));
        mHeaders.put(Const.CommonHttpHeader.VS, AppInfo.getVersionCode());
        mHeaders.put(Const.CommonHttpHeader.WV, "unknow");
        mHeaders.put(Const.CommonHttpHeader.ML, SysInfo.getMobileModel());
        mHeaders.put(Const.CommonHttpHeader.ID, DeviceInfo.getDeviceId(ContextHolder.getContext()));
        mHeaders.put(Const.CommonHttpHeader.OS, SysInfo.getSDKVersion());
        mHeaders.put(Const.CommonHttpHeader.CR, DeviceInfo.getMobileService(ContextHolder.getContext()));
        mHeaders.put(Const.CommonHttpHeader.CH, "1");
        mHeaders.put(Const.CommonHttpHeader.LE, SysInfo.getLanguage());
    }

    public static CommonHeaderInterceptor getInstance() {

        if (mCommonHeaderInterceptor == null) {
            synchronized (CommonHeaderInterceptor.class) {
                if (mCommonHeaderInterceptor == null) {
                    mCommonHeaderInterceptor = new CommonHeaderInterceptor();
                }
            }
        }

        return mCommonHeaderInterceptor;
    }


    public void addCommonHeader(String key, String value) {
        mHeaders.put(key, value);
    }


    @Override
    public Response intercept(Chain chain) throws IOException {
        Request.Builder builder = chain.request().newBuilder();

        Set<Map.Entry<String, String>> entrySet = mHeaders.entrySet();

        for (Map.Entry<String, String> entry : entrySet) {
            builder.addHeader(entry.getKey(), entry.getValue());
        }

        return chain.proceed(builder.build());
    }
}
